let num = 0
let select = true
let OPENID
let cartID = ''
Page({
  data: {
    carts:[],               // 购物车列表
    hasList:false,          // 列表是否有数据
    totalPrice:0,           // 总价，初始为0
    selectAllStatus:false,    // 全选状态，默认全选
    totalCount: 0,          //选中的商品数量
  },
  onLoad: function (options) {
    OPENID = options.OpenID
    this.getshoppingCart(options.OpenID)
 //   this.getCart(options.OpenID)
  //  this.changeNum()
  },
  onShow() {
    this.setData({
      hasList: true,        // 既然有数据了，那设为true吧
    });
  },
  getshoppingCart(OPENID){
    let ID = ''
    let NUM = 0
      wx.cloud.database().collection('shopping-cart')
      .where({
          openid:OPENID,
      })
      .get()
      .then(res=>{
        this.setData({
          carts:[]
        })
        console.log('商品id列表获取成功',res)
        cartID = res.data[0]._id
        console.log('cartID:',cartID)
        for (let index = 0; index < res.data[0].goods.length; index++) {
           ID = res.data[0].goods[index].id
           NUM = res.data[0].goods[index].num
           this.getIDGoods(ID,NUM)
        }

      })
      .catch(err=>{
        console.log('条件查询失败',err)
      })
  },
  getIDGoods(id,Num){
    var Goods = {}
    let IDDD = id
    wx.cloud.database().collection('send-Goods')
    .doc(IDDD)
    .get()
    .then(res=>{
      console.log('--------res为-----:',res)
      Goods = res.data
      ///////////////////////////////
      Goods.addnum = Num
      this.setData({
        carts:this.data.carts.concat(Goods)
      })
      console.log('--------Goods为-----:',Goods)
    })
    .catch(err=>{
      console.log('商品属性查询失败',err)
    })    
  },
  // ---------------------------
  //设置文本框值
  bindIptCartNum: function (e) {
    const index = e.currentTarget.dataset.index;
    var num = e.detail.value;
    let carts = this.data.carts;
    carts[index].addnum = parseInt(num) ;
    let binGoodsID = carts[index]._id
    this.setData({
      carts: carts
    });
    console.log('------num--------',num)
    wx.cloud.database().collection('shopping-cart')
    .doc(cartID)
    .get()
    .then(res=>{
      console.log('查询购物车成功：',res)
      for (let AA = 0; AA < res.data.goods.length; AA++) {
        let forID = res.data.goods[AA].id
        if(binGoodsID==forID)
         {
          console.log('进入if')
          if(num!='')
           this.changeNum(num,AA,cartID,0)
         }
      }
    })
    .catch(err=>{
      console.log('条件查询失败',err)
    })
  },
 //修改num值
 changeNum(willNum,index,Cartid,type){
   wx.cloud.callFunction({
     name:'changeCartNum',
     data:{
       WillNum:willNum,
       index:index,
       cartID:Cartid,
       Type:type
     }
   }).then(res=>{
    console.log('文本框修改成功：',res)
  })
  .catch(err=>{
    console.log('文本框修改失败：',err)
  })
  console.log('调用修改')
 },
  /* 点击减号 */
  bindMinus: function (e) {
    const index = e.currentTarget.dataset.index;
    console.log('index:',index)
    let carts = this.data.carts;
    let num = carts[index].addnum;
    let binGoodsID = carts[index]._id
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    carts[index].addnum = num;
    this.setData({
      carts: carts
    });
    wx.cloud.database().collection('shopping-cart')
    .doc(cartID)
    .get()
    .then(res=>{
      console.log('查询购物车成功：',res)
      for (let AA = 0; AA < res.data.goods.length; AA++) {
        let forID = res.data.goods[AA].id
        if(binGoodsID==forID)
         {
          console.log('进入if')
          if(num!='')
           this.changeNum(num,AA,cartID,2)
         }
      }
    })
    .catch(err=>{
      console.log('条件查询失败',err)
    })
    this.getTotalPrice();
  },
 
  /* 点击加号 */
  bindPlus: function (e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = parseInt(carts[index].addnum) ;
    let binGoodsID = carts[index]._id
    num = num + 1;
    carts[index].addnum = num;
    this.setData({
      carts: carts
    });
    wx.cloud.database().collection('shopping-cart')
    .doc(cartID)
    .get()
    .then(res=>{
      console.log('查询购物车成功：',res)
      for (let AA = 0; AA < res.data.goods.length; AA++) {
        let forID = res.data.goods[AA].id
        if(binGoodsID==forID)
         {
          console.log('进入if')
          if(num!='')
           this.changeNum(num,AA,cartID,1)
         }
      }
    })
    .catch(err=>{
      console.log('条件查询失败',err)
    })
    this.getTotalPrice();
  },
 
  //删除商品
  bindCartsDel(e) {
    var that = this;
    const did = e.currentTarget.dataset.bid
    console.log('要删除的购物车商品id:',did)
    wx.showModal({
      title: '提示',
      content: '您确定要删除吗？',
      success: function (res) {
        if (res.confirm) {
          //网络请求删除购物车数据
                //云函数删除
                wx.cloud.callFunction({
                  name:'deleteCart',
                  data:{
                     id:did,
                  }
                })
                .then(res=>{
                  wx.showToast({
                    title: '删除成功',
                    icon:'none'
                  })
                  console.log('云函数删除成功',res)
                  that.getshoppingCart(OPENID)
                })
                .catch(err=>{
                  console.log('云函数删除失败',err)
                })
        }
      }
    })
  },
  //计算总价
  getTotalPrice() {
    let carts = this.data.carts;                  // 获取购物车列表
    let total = 0;
    let num = 0;
    for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
      if (carts[i].isSelect) {                   // 判断选中才会计算价格
        total += carts[i].addnum * carts[i].price;    // 所有价格加起来
        num +=parseInt(carts[i].addnum) ;
      }
    }
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      totalCount: num,
      totalMoney: total.toFixed(2)
    });
  },
 
  //绑定单选
  bindCheckbox: function (e) {
    var that = this;
    const idx = e.currentTarget.dataset.index;
    let carts = that.data.carts;
    const isSelect1 = carts[idx].isSelect;
    carts[idx].isSelect = !isSelect1;
    that.setData({
      carts: carts,
      selectAllStatus: false
    });
    that.getTotalPrice();
  },
 
 
  //绑定多选
  bindSelectAll: function (e) {
    var that = this;
    let selectedAllStatus = that.data.selectAllStatus;
    let carts = that.data.carts;
    selectedAllStatus = !selectedAllStatus;
    for (var i = 0; i < carts.length; i++) {
      carts[i].isSelect = selectedAllStatus;
    }
 
    that.setData({
      carts: carts,
      selectAllStatus: selectedAllStatus
    });
    that.getTotalPrice();
  },
 
  //购物车结算
  bindjiesuan: function () {
    var that = this;
    let carts = that.data.carts;
    let jscart = [];
    let buyNum = 0
    var j = 0
    for (var i = 0; i < carts.length; i++) {
      if (carts[i].isSelect) {
        jscart[j] = carts[i];
        j++;
      }
    }
    if (jscart.length <= 0) {
      wx.showToast({
        title: '未选择商品',
        icon: 'success',
        duration: 1000
      })
      return;
    }
    console.log('已选择的商品jscart：',jscart)
    // wx.setStorageSync('jscart', jscart);//存入缓存
    //转到结算页面
    wx.showToast({
      title: '暂不支持多商品结算，请点击商品单个购买',
      icon:'none'
    })
    // wx.navigateTo({
    //   // url: '/pages/ShoppingCartSettlement/ShoppingCartSettlement?amount=' + that.data.totalMoney
    //   url: '/pages/ShoppingCartSettlement/ShoppingCartSettlement?array=' + encodeURIComponent(JSON.stringify(jscart))
    //   +'&amount=' + that.data.totalMoney
    // });
  },
  goDetail(e){
    console.log('点击了商品详情页',e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '/pages/details/details?id='+e.currentTarget.dataset.id,
    })
  }
})